package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowModelProcdef;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowModelProcdefRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowModelProcdefInfoDAO;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowModelProcdefInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowModelProcdefInfoExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author cheng.huaxing
 * @date 2019-02-03
 */
@Service
public class FlowModelProcdefRepositoryImpl implements FlowModelProcdefRepository {

    @Autowired
    private FlowModelProcdefInfoDAO flowModelProcdefInfoDAO;

    @Override
    public Integer insert(FlowModelProcdef modelProcdefInfo) {
        FlowModelProcdefInfo entity = new FlowModelProcdefInfo();
        BeanUtils.copyProperties(modelProcdefInfo, entity);
        flowModelProcdefInfoDAO.insert(entity);
        return entity.getId();
    }

    @Override
    public FlowModelProcdef getModelProcDef(String procDefId) {
        if (StringUtils.isEmpty(procDefId)) {
            return null;
        }
        FlowModelProcdefInfoExample example = new FlowModelProcdefInfoExample();
        example.createCriteria().andProcdefIdEqualTo(procDefId);
        List<FlowModelProcdefInfo> flowModelProcdefInfos = flowModelProcdefInfoDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(flowModelProcdefInfos)) {
            return null;
        }
        return convert(flowModelProcdefInfos.get(0));
    }

    @Override
    public List<FlowModelProcdef> getModelProcDefByModelId(String modelId) {
        if (StringUtils.isEmpty(modelId)) {
            return null;
        }
        FlowModelProcdefInfoExample query = new FlowModelProcdefInfoExample();
        query.createCriteria().andModelIdEqualTo(modelId);
        return flowModelProcdefInfoDAO.selectByExample(query).stream().map(this::convert).collect(Collectors.toList());
    }

    private FlowModelProcdef convert(FlowModelProcdefInfo info) {
        if (Objects.isNull(info)) {
            return null;
        }
        FlowModelProcdef result = new FlowModelProcdef();
        BeanUtils.copyProperties(info, result);
        return result;
    }
}
